<?php

namespace App\Listeners;

use App\Events\SalesNumber;
use App\SpecGoodsPrice;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleSalesNumber
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SalesNumber  $event
     * @return void
     */
    public function handle(SalesNumber $event)
    {
        $order = $event->order;
        if ($order && $order->orderGoods->count() > 0) {
            foreach ($order->orderGoods as $orderGoods) {
                $goods = $orderGoods->goods;
                if ($goods) {
                    $goods->increment('sales_count', $orderGoods->goods_num * $event->algorithm);
                    $goods->decrement('stock', $orderGoods->goods_num * $event->algorithm);
                    if ($orderGoods->spec_key) {
                        $spec = SpecGoodsPrice::where('key', $orderGoods->spec_key)->first();
                        if ($spec) {
                            $spec->decrement('stock', $orderGoods->goods_num * $event->algorithm);
                        }
                    }
                }
            }
        }
    }
}
